# Copyright (c) 2011 Sergey K.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.


import re

from inspect import getargspec
from threading import RLock
from types import FunctionType, ClassType, TypeType

from rs.core import has_rs, get_rs


__all__ = [
    'Resource',
    'build',
    'build_all',
]


class Resource(object):
    
    def __init__(self):
        self.method = None
        self.path = None
        self.pattern = None
        self.consumer = None
        self.producer = None
        self.target = None
        self.type = None

    def __hash__(self):
        return hash(self.target) # for set()

    
class ResourceBuilder(object):

    def __init__(self, buildobj, _extends=None):
        if not isinstance(buildobj, (ClassType, TypeType, FunctionType)):
            raise TypeError(
                'Unexpected type: {0}, must be class or function'
                .format(buildobj))
        self.buildobj = buildobj
        self._extends = []
        if _extends:
            self._extends.extend(_extends)

    def build(self):
        if isinstance(self.buildobj, (ClassType, TypeType)):
            return self.build_resources()
        elif isinstance(self.buildobj, FunctionType) and has_rs(self.buildobj):
            return [self.build_resource(target=self.buildobj)]
        return []

    def build_resources(self):
        resources = []
        if has_rs(self.buildobj):
            self._extends.append(get_rs(self.buildobj))
        for v in vars(self.buildobj).itervalues():
            if isinstance(v, (ClassType, TypeType)):
                resources.extend(ResourceBuilder(v,
                                    self._extends).build_resources())
            elif isinstance(v, FunctionType):
                if has_rs(v):
                    resources.append(self.build_resource(target=v,
                                                         type=self.buildobj))
        return resources

    def build_resource(self, target, type=None):
        resource = Resource()
        resource.target = target
        def combine_extends(rs_):
            for k,v in rs_.iteritems():
                if k == 'path':
                    resource.path = ((resource.path or '').rstrip('/\\')
                                     + '/' + v.strip('/'))
                elif k in resource.__dict__:
                    resource.__dict__[k] = v
        if self._extends:
            for e in self._extends:
                combine_extends(e)
        combine_extends(get_rs(resource.target))
        if not resource.path:
            resource.path = '/'
        pattern = resource.path
        params = []
        for i, p in enumerate(re.findall('\{(.+?)\}', resource.path)):
            pattern = pattern.replace('{{{0}}}'.format(p), '{{{0}}}'.format(i))
            params.append(self.create_path_parameter(p))
        pattern = pattern.replace('\\', '/')
        if params:
            pattern = pattern.format(*params)
        resource.pattern = re.compile('^{0}$'.format(pattern.strip('/')))
        if type:
            resource.type = type
        return resource

    @staticmethod
    def create_path_parameter(param):
        p = param.partition(':')
        return '(?P<{0}>{1})'.format(p[0].strip(), p[2].strip() or '.+')


def build(resource):
    return ResourceBuilder(resource).build()


def build_all(resources):
    resources = set(resources)
    for c in [c for c in resources if isinstance(c, (ClassType, TypeType))]:
        for f in [f for f in vars(c).itervalues() if isinstance(f,
            (ClassType, TypeType, FunctionType))]:
            if has_rs(f):
                resources.discard(f)
    resources = sum(map(build, resources), [])
    return resources


class ResourceManager(set):

    def __init__(self, resources=()):
        super(ResourceManager, self).__init__(resources)
        self.args = {}
        self.instances = {}
        self.__instance_lock = RLock()
        self.__args_lock = RLock()

    def get_instance(self, resource):
        assert resource.type
        if resource.type not in self.instances:
            with self.__instance_lock:
                if resource.type not in self.instances:
                    self.instances[resource.type] = resource.type()
        return self.instances[resource.type]

    def get_args(self, resource):
        assert resource.target
        if resource.target not in self.args:
            with self.__args_lock:
                if resource.target not in self.args:
                    argspec = getargspec(resource.target)
                    argdefs = {}
                    if argspec.defaults:
                        argdefs.update(
                            zip(argspec.args[-len(argspec.defaults):],
                                argspec.defaults)
                        )
                    self.args[resource.target] = argspec, argdefs
        return self.args[resource.target]